package com.kmis.controllers;

import com.kmis.web.ApiResult;
import org.springframework.dao.DataAccessException;
import org.springframework.web.bind.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import com.kmis.services.IUserService;
import com.kmis.entities.User;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiImplicitParam;


/**
 * 用户控制层。
 *
 * @author MLB
 * @since 1.0
 */
@RestController
@RequestMapping("/User/")
@Api(tags = "")
public class UserController {

    private final IUserService userService;
    @Autowired
    public UserController(IUserService userService) {
        this.userService = userService;
    }

    @PostMapping("insert")
    @ApiOperation(value = "新增用户",notes="新增用户")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "user",value = "用户对象",required = true)
    })
    public ApiResult insert(@RequestBody User user){
        try{
            return userService.insertUser(user);
        }catch(DataAccessException e){
            return ApiResult.error(-1,"参数错误");
        }
    }

    @DeleteMapping("delete/{id}")
    @ApiOperation(value = "删除用户（逻辑删除）",notes="删除用户（逻辑删除）")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "id",value="主键",required = true)
    })
    public ApiResult delete(@PathVariable Integer id){
        return userService.removeUserById(id);
    }

    @ApiOperation(value = "更新用户",notes="更新用户")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "user",value="更新的用户对象",required = true)
    })
    @PostMapping("update")
    public ApiResult update(@RequestBody User user){
        return userService.updateUser(user);
    }

    @ApiOperation(value = "分页查询用户",notes="分页查询用户")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "pageNumber",value="当前页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页显示最大数",required = true)
    })
    @GetMapping("page/{pageNumber}/{pageSize}")
    public ApiResult page(@PathVariable Integer pageNumber,@PathVariable Integer pageSize){
        return userService.page(pageNumber,pageSize);
    }

    @ApiOperation(value = "模糊查询用户",notes="模糊查询用户")
    @ApiImplicitParams(value = {
            @ApiImplicitParam(name = "pageNumber",value="当前页码",required = true),
            @ApiImplicitParam(name = "pageSize",value = "每页显示最大数",required = true)
    })
    @GetMapping("search")
    public ApiResult search(@RequestParam(defaultValue = "") String nickname,
                            @RequestParam(defaultValue = "") String phone,
                            @RequestParam(defaultValue = "") String status,
                            @RequestParam int pageNumber,
                            @RequestParam int pageSize){
        return userService.search(nickname, phone, status, pageNumber, pageSize);
    }
}